<template>
  <div class="dashboard-container">

    <!-- 搜索筛选 -->
    <div class="search">
      <el-button type="primary" @click="handleSearch" size="mini">刷新</el-button>
      <el-button type="primary" @click="handleAdd('create')" size="mini">新增报告</el-button>
    </div>


    <!-- 数据列表 -->
    <el-table :data="list" v-loading="loading">
      <el-table-column prop="serialNumber" label="业务编号"></el-table-column>
      <el-table-column prop="codeName" label="报告编号"></el-table-column>
      <el-table-column prop="name" label="项目名称"></el-table-column>
      <el-table-column prop="customerCompanyBusiness.name" label="业务类型"></el-table-column>
      <el-table-column prop="customerCompany.name" label="客户公司"></el-table-column>
      <el-table-column prop="customerUser.realName" label="业务员"></el-table-column>
      <el-table-column prop="statusName" label="状态"></el-table-column>
      <el-table-column label="操作" width="150px">
        <template slot-scope="{row}">
          <el-button type="text" size="mini" @click="handleAdd('update', row)">查看报告</el-button>
          <el-button type="text" size="mini" @click="handleDelete(row.id)" style="color: red">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="page">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="params.pageIndex + 1" :page-sizes="[10, 20, 30, 40]" :page-size="params.pageCount"
        layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <!-- 新增、查看报告 -->
    <el-dialog :visible="visibleDialog" :close-on-click-modal="false" :title="dialogType == 'create' ? '新增报告' : '查看报告'"
      class="dialog" width="1000px" @close="visibleDialog = false">
      <!-- 操作栏 -->
      <div class="opt">
        <el-button type="primary" size="mini" @click="handeSave('close')">保存并关闭</el-button>
        <el-button type="primary" size="mini" @click="handeSave">保存</el-button>
        <!-- <el-button type="primary" size="mini">附件生成</el-button> -->
        <el-button type="primary" size="mini" @click="finishSurvey" v-if="temp.status == 1">完成勘察</el-button>
        <span v-if="temp.status == 2" style="margin-left: 8px;">
          <el-button type="primary" size="mini" @click="handleReportFile(1)">生成报告数据附件</el-button>
          <el-button type="primary" size="mini" @click="handleReportFile(2)">生成报告文档附件</el-button>
          <el-button type="primary" size="mini" @click="handleReportFile(3)">生成评估对象数据附件</el-button>
        </span>
      </div>
      <!-- 内容栏 -->
      <div class="content">
        <div class="sub_title">委托信息</div>
        <el-form :inline="true" size="mini" class="form-grid">
          <el-form-item label="项目名" required>
            <el-input placeholder="请输入项目名" v-model="temp.name"></el-input>
          </el-form-item>
          <el-form-item label="首次再次类型" required>
            <el-select v-model="temp.againType" :disabled="dialogType == 'update'">
              <el-option v-for="item in AGAIN_TYPE_LIST" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="客户公司业务类型" required>
            <el-select v-model="temp.customerCompanyBusinessEiid" filterable>
              <el-option v-for="item in customerCompanyBusinessesList" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="客户人员" required>
            <span style="margin-right: 10px">{{ temp.customerUser ? temp.customerUser.realName : "" }}</span>
            <el-button type="text" @click="handleSelectUser" v-if="dialogType == 'create'">选择</el-button>
          </el-form-item>
          <el-form-item label="评估方法类型">
            <el-select v-model="temp.methodTypeEiids" filterable multiple>
              <el-option v-for="item in METHOD_TYPE_LIST" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="目标类型" required>
            <el-select v-model="temp.purposeType" filterable :disabled="dialogType == 'update'">
              <el-option v-for="item in PURPOSE_TYPE_LIST" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div class="sub_title">委托对象</div>
        <div v-if="dialogType=='create'">
          <el-select size="mini" v-model="propertyType">
            <el-option v-for="item, index in TARGET_TYPE_LIST" :value="item.value" :label="item.label"
              :key="index"></el-option>
          </el-select>
          <el-button type="primary" size="mini" @click="handleAddSubject">添加委托对象</el-button>
        </div>
        <el-table :data="temp.subjects" size="mini">
          <el-table-column label="名称" prop="name"></el-table-column>
          <el-table-column label="资产类型" prop="propertyTypeName"></el-table-column>
          <el-table-column label="面积(㎡)" prop="area"></el-table-column>
          <el-table-column label="状态" prop="statusName"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="{row, $index}">
              <el-button type="text" size="mini" @click="handleFinishSurvey(row.survryId)"
                v-if="row.survryId && row.statusName == '未查勘'">完成查勘</el-button>
              <el-button type="text" size="mini" @click="topSubject($index)" v-if="$index!=0">置顶</el-button>
              <el-button type="text" size="mini" style="color: red;" @click="deleteSubject($index)" v-if="dialogType=='create'">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="sub_title">报告信息</div>
        <el-form :inline="true" size="mini" class="form-grid">

          <el-form-item label="报告编号" v-if="temp.id">
            <span>{{ temp.codeName }}</span>
            <el-button type="text" size="mini" @click="handleGetCode" v-if="!temp.codeName">生成编号</el-button>
          </el-form-item>
          <el-form-item label="第一估价师" required>
            <span style="margin-right: 10px">{{ temp.primaryUser ? temp.primaryUser.realName : "" }}</span>
            <el-button type="text" @click="handleSelectUser2('primaryUserId')">选择</el-button>
          </el-form-item>
          <el-form-item label="第二估价师">
            <span style="margin-right: 10px">{{ temp.secondaryUser ? temp.secondaryUser.realName : "" }}</span>
            <el-button type="text" @click="handleSelectUser2('secondaryUserId')" >选择</el-button>
          </el-form-item>
          <el-form-item label="审核估价师">
            <span style="margin-right: 10px">{{ temp.reviewUser ? temp.reviewUser.realName : "" }}</span>
            <el-button type="text" @click="handleSelectUser2('reviewUserId')" >选择</el-button>
          </el-form-item>
          <el-form-item label="撰写人员">
            <span style="margin-right: 10px">{{ temp.writeUser ? temp.writeUser.realName : "" }}</span>
            <el-button type="text" @click="handleSelectUser2('writeUserId')" >选择</el-button>
          </el-form-item>
          <el-form-item label="完成时间" required v-if="temp.status==2">
            <el-date-picker v-model="temp.finishTime" value-format="timestamp" type="date" placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="价值时点" required v-if="temp.status==2">
            <el-date-picker v-model="temp.evaluateTime" value-format="timestamp" type="date" placeholder="选择日期">
            </el-date-picker>
          </el-form-item>

          <!-- 自定义字段 -->
          <el-form-item :label="item.name" required v-for="(item, index) in fieldList" :key="index">
            <el-input v-model="temp.fields[index]['stringValue']" :placeholder="'请输入' + item.name"
              v-if="item.showType == 0 && item.valueType == 2"></el-input>
            <el-input v-model="temp.fields[index]['decimalValue']" :placeholder="'请输入' + item.name"
              v-if="item.showType == 0 && item.valueType == 0"></el-input>
            <el-select v-model="temp.fields[index]['enumItemName']" v-if="item.showType == 3">
              <el-option v-for="enumItem in item.relatedEnum.items" :label="enumItem.name" :value="enumItem.name"
                :key="enumItem.id"></el-option>
            </el-select>
            <div v-if="item.showType == 5">
              <el-radio v-model="temp.fields[index]['longValue']" :label="1">是</el-radio>
              <el-radio v-model="temp.fields[index]['longValue']" :label="0">否</el-radio>
            </div>
            <el-date-picker v-model="temp.fields[index]['longValue']" type="date" placeholder="选择日期"
              style="width: 100%;" v-if="item.showType == 2" value-format="timestamp">
            </el-date-picker>

            <el-input v-if="temp.showType == 1" type="textarea" :rows="2" v-model="temp.fields[index]['stringValue']"
              placeholder="请输入"></el-input>
          </el-form-item>
          

        </el-form>
        <div class="sub_title">附件信息</div>
        <el-table :data="temp.files" size="mini">
          <el-table-column label="文件名" prop="showName"></el-table-column>
          <el-table-column label="描述" prop="description"></el-table-column>
          <el-table-column label="操作">
            <template slot-scope="{row, $index}">
              <!-- <el-button type="text" size="mini">编辑</el-button> -->
              <el-button type="text" size="mini" style="color: red;" @click="handleDeleteFile($index)">删除</el-button>
              <el-button type="text" size="mini" @click="handleDownloadFile(row.url, row.showName)">下载</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

    </el-dialog>

    <!-- 选择人员 -->
    <el-dialog :visible="visibleDialogUser" title="选择人员" @close="visibleDialogUser = false"
      :close-on-click-modal="false" class="dialogUser dialog">
      <el-cascader clearable v-model="companyId" :options="companyList" size="mini" @change="changeCompanyVal">
      </el-cascader>
      <el-button type="primary" size="mini" @click="visibleDialogUser = false">确认</el-button>
      <el-table :data="UserList">
        <el-table-column label="选择" width="50px">
          <template slot-scope="scope">
            <el-radio v-model="selectUser" :label="scope.row.id" @change="selectUserVal"></el-radio>
          </template>
        </el-table-column>
        <el-table-column label="公司" prop="company.name"></el-table-column>
        <el-table-column label="昵称" prop="realName"></el-table-column>
      </el-table>
      <div class="page">
        <el-pagination @size-change="(val) => handleSizeChange(val, 'paramsUser')"
          @current-change="(val) => handleCurrentChange(val, 'paramsUser')" :current-page="paramsUser.pageIndex + 1"
          :page-sizes="[10, 20, 30, 40]" :page-size="paramsUser.pageCount"
          layout="total, sizes, prev, pager, next, jumper" :total="userTotal">
        </el-pagination>
      </div>
    </el-dialog>

    <!-- 选择人员(内部) -->
    <el-dialog :visible="visibleDialogUser2" title="选择人员" @close="visibleDialogUser2 = false"
      :close-on-click-modal="false" class="dialogUser dialog">
      <el-button type="primary" size="mini" @click="visibleDialogUser2 = false">确认</el-button>
      <el-table :data="UserList">
        <el-table-column label="选择" width="50px">
          <template slot-scope="scope">
            <el-radio v-model="selectUser2" :label="scope.row.id" @change="selectUserVal2"></el-radio>
          </template>
        </el-table-column>
        <el-table-column label="公司" prop="company.name"></el-table-column>
        <el-table-column label="昵称" prop="realName"></el-table-column>
      </el-table>
      <div class="page">
        <el-pagination @size-change="(val) => handleSizeChange(val, 'paramsUser')"
          @current-change="(val) => handleCurrentChange(val, 'paramsUser')" :current-page="paramsUser.pageIndex + 1"
          :page-sizes="[10, 20, 30, 40]" :page-size="paramsUser.pageCount"
          layout="total, sizes, prev, pager, next, jumper" :total="userTotal">
        </el-pagination>
      </div>
    </el-dialog>


    <!-- 新增评估对象 -->
    <el-dialog title="新增委托对象" :visible="isibleDialogSubject" @close="isibleDialogSubject = false"
      :close-on-click-modal="false">
      <el-form ref="form" :model="tempSubject" :rules="rulesSubject" label-width="140px">
        <el-form-item label="名称" prop="name">
          <el-input placeholder="请输入名称" v-model="tempSubject.name"></el-input>
        </el-form-item>
        <el-form-item label="面积(m²)" prop="area">
          <el-input type="number" placeholder="请输入面积" v-model="tempSubject.area"></el-input>
        </el-form-item>
        <!-- 动态字段 -->
        <el-form-item v-for="item, index in tempSubject.fields" :key="index"
          :label="item.name + (item.valueUnit ? `(${item.valueUnit})` : '') + ':'" :required="item.requiredFlag == 1">
          <el-input v-model="tempSubject.fields[index]['stringValue']" :placeholder="'请输入' + item.name"
            v-if="item.showType == 0 && item.valueType == 2"></el-input>
          <el-input v-model="tempSubject.fields[index]['decimalValue']" :placeholder="'请输入' + item.name"
            v-if="item.showType == 0 && item.valueType == 0"></el-input>
          <el-select v-model="tempSubject.fields[index]['enumItemName']" v-if="item.showType == 3">
            <el-option v-for="enumItem in item.relatedEnum.items" :label="enumItem.name" :value="enumItem.name"
              :key="enumItem.id"></el-option>
          </el-select>
          <div v-if="item.showType == 5">
            <el-radio v-model="tempSubject.fields[index]['longValue']" :label="1">是</el-radio>
            <el-radio v-model="tempSubject.fields[index]['longValue']" :label="0">否</el-radio>
          </div>
          <el-date-picker v-model="tempSubject.fields[index]['longValue']" type="date" placeholder="选择日期"
            style="width: 100%;" v-if="item.showType == 2" value-format="timestamp">
          </el-date-picker>

          <el-input v-if="item.showType == 1" type="textarea" :rows="2"
            v-model="tempSubject.fields[index]['stringValue']" placeholder="请输入"></el-input>

        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input type="textarea" :rows="2" placeholder="请输入描述" v-model="tempSubject.description"></el-input>
        </el-form-item>
        <el-form-item label="相关案例">
          <el-button type="primary" size="mini" @click="handleAddCase">选择案例</el-button>
          <el-table :data="tempSubject.relatedTarget" size="mini">
            <el-table-column label="城市" prop="cityName"></el-table-column>
            <el-table-column label="案例名称" prop="name"></el-table-column>
            <el-table-column label="小区名" prop="community.name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="{row, $index}">
                <el-button type="text" size="mini" style="color: red" @click="handleDeleteCase($index)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div style="text-align: right;">
        <el-button type="primary" @click="submitSubject('form')">提交</el-button>
        <el-button @click="isibleDialogSubject = false">关闭</el-button>
      </div>
    </el-dialog>


    <!-- 生成附件 -->
    <el-dialog :title="dialogTitle" :visible="visibleDialogFile" @close="visibleDialogFile = false" width="500px">
      <el-form ref="formFile" :model="tempFile" size="mini" label-width="140px">
        <el-form-item label="报告附件分类">
          <el-select v-model="tempFile.categoryEiid">
            <el-option v-for="item in fileEiidList" :label="item.label" :value="item.value"
              :key="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="附件显示名">
          <el-input placeholder="请输入附件显示名" v-model="tempFile.showName"></el-input>
        </el-form-item>
        <el-form-item label="附件描述">
          <el-input placeholder="请输入描述" v-model="tempFile.description"></el-input>
        </el-form-item>
        <el-form-item label="报告模板" required>
          <el-select v-model="tempFile.reportTemplateId">
            <el-option v-for="item in reportTemplateList" :label="item.label" :value="item.value"
              :key="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="评估对象" required v-if="fileReportType == 3">
          <el-select v-model="tempFile.subjectId">
            <el-option v-for="item in subjectFileList" :label="item.label" :value="item.value"
              :key="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="mini" @click="submitFile">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 选择案例 -->
    <el-dialog title="选择相关案例" :visible="visibleDialogCase" @close="visibleDialogCase = false" width="800px">
      <el-select filterable clearable v-model="paramsCase.cityId" placeholder="请选择" size="mini">
        <el-option v-for="item, index in cityList" :key="index" :label="item.label" :value="item.value"></el-option>
      </el-select>
      <el-input placeholder="请输入案例名称" v-model="paramsCase.name" size="mini" style="width:120px"></el-input>
      <el-button type="primary" size="mini" @click="getCaseList">查询</el-button>
      <el-table :data="CaseList" size="mini">
        <el-table-column label="城市" prop="cityName"></el-table-column>
        <el-table-column label="案例名称" prop="name"></el-table-column>
        <el-table-column label="小区名" prop="community.name"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="{row, $index}">
            <el-button type="text" size="mini" @click="handleSelectCase(row)">选择</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <div class="page">
        <el-pagination @size-change="(val) => handleSizeChange(val, 'paramsCase')" @current-change="(val) => handleCurrentChange(val, 'paramsCase')"
          :current-page="paramsCase.pageIndex + 1" :page-sizes="[10, 20, 30, 40]" :page-size="paramsCase.pageCount"
          layout="total, sizes, prev, pager, next, jumper" :total="totalCase">
        </el-pagination>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import {
  reportGetList, reportDelete, reportCreate, reportCancel, reportInfo, reportSubmit, reportSurvey, reportUpdate, reportWrite, reportExport, reportGetExportFieldOptions, reportGenerateCode,
  reportGenerateFileByReportDataTemplate, reportGenerateFileByReportDocTemplate, reportGenerateFileBySubjectDataTemplate
} from '@/api/report'
import { AGAIN_TYPE_LIST, PURPOSE_TYPE_LIST, TARGET_TYPE_LIST, REPORT_STATUS_LIST, SURVEY_STATUS_LIST } from '@/utils/common'
import { downloadFile, transfromData, treeTransForm } from '@/utils/tools'
import { fieldGetList } from '@/api/field'
import { enumInfo } from '@/api/enum'
import { userGetList } from '@/api/user'
import { subjectCreate } from '@/api/subject'
import moment from 'moment'
import { surveyGetList, surveyFinish } from '@/api/survey'
import { companyGetTree } from '@/api/company'
import { reportTemplateGetList } from '@/api/reportTemplate'
import { targetGetList } from '@/api/target'
import { commonGetCityList } from '@/api/common'

let temp = {
  againType: 1,  //首次再次类型
  customerCompanyBusinessEiid: '',  //客户公司业务类型EIID
  customerUserId: '', //客户人员ID
  fields: [],  //字段列表[{’fieldId’:1, 'longValue’:1, 'stringValue’:’abc’, decimalValue:1.23, enumItemNames:['abc’,’edf’,…], enumItemName:’abc’},…]
  files: [], //文件列表[{’description’: '描述’, 'showName’:’现场图片.jpg’, 'url’:’/rest/202410/abc.jpg’, 'categoryEiid’:1},…]
  methodTypeEiids: [], //评估方法类型EIID列表[1,2,3,…]
  name: '', //项目名称
  primaryUserId: '', //第一估价师ID
  purposeType: '', //目标类型
  reportType: 1, //报告类型
  reviewUserId: '', //审核估价师ID
  secondaryUserId: '', // 第二估价师ID
  subjectIds: [], //评估对象ID列表[1,2,3,…]
  submitFlag: 1, //是否立即申请 
  writeUserId: '',  //撰写人员ID

  subjects: [],//非正式参数，对象列表 subjects
  customerUser: {}, //非正式参数，客户人员对象 subjects
  primaryUser: {}, 
  secondaryUser: {},
  reviewUser: {},
  writeUser: {}
}

let tempSubject = {
  area: '', name: '', description: '', fields: [], files: [], latitude: '', longitude: '', propertyType: '', relatedTargetIds: [], relatedTarget:[]
}

export default {
  name: 'Staffuser',
  computed: {
    ...mapGetters([
      'name'
    ])
  },
  data() {
    return {
      AGAIN_TYPE_LIST,
      PURPOSE_TYPE_LIST,
      TARGET_TYPE_LIST,
      REPORT_STATUS_LIST,
      SURVEY_STATUS_LIST,
      METHOD_TYPE_LIST: [],
      loading: false,
      cityList: [],// 城市列表
      params: {
        pageIndex: 0,
        pageCount: 10
      },
      total: 0,
      list: [],
      visibleDialog: false,
      dialogType: 'create',
      temp: {},
      customerCompanyBusinessesList: [],
      fieldList: [], //报告自定义字段列表
      visibleDialogUser: false, //选择人员
      visibleDialogUser2: false, //选择人员 -内部
      UserList: [], //选择的人员列表
      userTotal: 0,
      paramsUser: {},
      selectUser: '',
      selectUser2: '',
      propertyType: 1,//公共参数
      tempSubject: {}, //创建委托对象
      isibleDialogSubject: false,
      rulesSubject: {
        name: [{ required: true, message: '请输入项目名', trigger: 'blur' }],
        area: [{ required: true, message: '请输入面积', trigger: 'blur' }],
      },
      companyList: [],
      companyId: '',
      fileReportType: '',
      visibleDialogFile: false,
      dialogTitle: '生成报告数据附件',
      tempFile: {},
      fileEiidList: [], //报告附件分类
      reportTemplateList: [], //报告模板id
      subjectFileList: [], //评估对象
      visibleDialogCase: false,
      paramsCase: {},
      totalCase: 0,
      CaseList: [],
      dialogTypeUser: false,
      selectUserType: ''
    }
  },
  async mounted() {
    let citys = await commonGetCityList({ geoLevel: 2, provinceId: 11 });
    this.cityList = citys.map(item => {
      return { label: item.name, value: item.id }
    })
    //获取公司列表
    let data = await companyGetTree({ userType: 2 })
    //默认最高5级
    this.companyList = treeTransForm(data)

    //获取所有报告附件分类
    let EiidList = await enumInfo({ id: 40 })
    this.fileEiidList = EiidList.items.filter(item => item.selectFlag == 1).map(item => {
      let name = item.name;
      let nowItem = JSON.parse(JSON.stringify(item));
      for (let i = 1; i < item.level; i++) {
        let parent = EiidList.items.filter(aItem => aItem.id == nowItem.parentId);
        if (parent.length > 0) {
          name = parent[0].name + '-' + name
        }
        nowItem = parent;
      }
      return { label: name, value: item.id }
    })

    this.handleSearch();
  },

  methods: {
    // 删除附件
    handleDeleteFile(index){
      this.temp.files.splice(index, 1)
    },
    //置顶当前的委托对象
    topSubject(index){
      let elemet = this.temp.subjects.splice(index, 1)[0]
      this.temp.subjects.unshift(elemet)
      this.subjectIds = this.temp.subjects.map(item=>item.id)
    },
    //删除已选择的相关案例
    handleDeleteCase(index){
      this.tempSubject.relatedTarget.splice(index, 1)
      this.relatedTargetIds = this.tempSubject.relatedTarget.map(item=>item.id)
    },
    //点击选择按钮
    handleAddCase() {
      this.visibleDialogCase = true;
      // 加载案例列表接口
      this.paramsCase = {
        pageIndex: 0,
        pageCount: 10,
        name: '',
        propertyTypes: [this.propertyType],
        provinceId: 11,
        cityId: ''
      }
      this.getCaseList();
    },
    //获取案例列表数据
    async getCaseList() {
      let data = await targetGetList(this.paramsCase)
      this.CaseList = data.list.map(item=>{
        item.cityName = transfromData(this.cityList, item.cityId)
        return item
      })
      this.totalCase = data.totalCount
    },
    //选择案例
    handleSelectCase(row) {
      if(this.tempSubject.relatedTarget.length>=3){
        this.$message.error({ message: '最多选择3个案例' })
        return;
      }
      this.visibleDialogCase = false;
      this.tempSubject.relatedTarget.push(row)
      this.tempSubject.relatedTargetIds = this.tempSubject.relatedTarget.map(item => item.id)
    },
    //点击下载
    handleDownloadFile(url, name) {
      downloadFile(url, name)
    },
    //完成对象的查勘
    async handleFinishSurvey(id) {
      await surveyFinish({ id })
      this.$message.success({ message: '完成查勘' })
      //刷新详情数据
      this.getReportInfo(this.temp.id);
    },
    //提交生成附件
    async submitFile() {
      if (this.fileReportType == 1) {
        await reportGenerateFileByReportDataTemplate(this.tempFile)
      }
      if (this.fileReportType == 2) {
        await reportGenerateFileByReportDocTemplate(this.tempFile)
      }
      if (this.fileReportType == 3) {
        await reportGenerateFileBySubjectDataTemplate(this.tempFile)
      }
      this.$message.success({ message: '已生成' })
      this.visibleDialogFile = false;
      // 刷新详情数据
      this.getReportInfo(this.temp.id)

    },
    //点击生成附件
    async handleReportFile(type) {
      this.fileReportType = type;
      let temp = {
        categoryEiid: '', //分类EIID
        description: '',  //附件描述
        id: this.temp.id,
        reportTemplateId: '',
        showName: '',   //附件显示名称
      }
      if (type == 1) {
        this.dialogTitle = '生成报告数据附件'
        let template = await reportTemplateGetList({ objectType: 7, templateType: 1 })
        this.reportTemplateList = template.list.map(item => {
          return { label: item.name, value: item.id }
        })
      }
      if (type == 2) {
        this.dialogTitle = '生成报告文档附件'
        let template = await reportTemplateGetList({ objectType: 7, templateType: 2 })
        this.reportTemplateList = template.list.map(item => {
          return { label: item.name, value: item.id }
        })
      }
      if (type == 3) {
        this.dialogTitle = '生成评估对象数据附件'
        let template = await reportTemplateGetList({ objectType: 8 })
        this.reportTemplateList = template.list.map(item => {
          return { label: item.name, value: item.id }
        })
        this.subjectFileList = this.temp.subjects.map(item => {
          return { label: item.name, value: item.id }
        })
        temp.subjectId = ''
      }
      this.tempFile = temp;
      this.visibleDialogFile = true;
    },
    // 修改公司数据
    changeCompanyVal(e) {
      this.paramsUser.companyId = e.length > 0 ? e[e.length - 1] : ''
      this.getUserList();
    },
    //完成勘察
    finishSurvey() {
      this.$confirm('请确保所有委托对象均已勘察, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await reportSurvey({ id: this.temp.id })
        this.getData();
        this.$message({
          type: 'success',
          message: '完成勘察!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //删除报告
    handleDelete(id) {
      this.$confirm('此操作将永久删除该报告, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await reportDelete({ ids: [id] })
        this.getData();
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //生成报告编号
    async handleGetCode() {
      if (this.temp.id) {
        await reportGenerateCode({ id: this.temp.id })
        this.$message.success({ message: '生成成功' })
        this.getReportInfo(this.temp.id);
      }
    },
    //删除评估对象
    deleteSubject(index) {
      this.temp.subjects.splice(index, 1)
      this.temp.subjectIds = this.temp.subjects.map(item => item.id)
    },
    //评估对象创建提交表单
    submitSubject(formName) {
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          let tempSubject = JSON.parse(JSON.stringify(this.tempSubject))
          delete tempSubject.relatedTarget
          // 判断一下自定义字段必填的内容是否都填写了 requiredFlag=1判断
          let error = [];
          tempSubject.fields.forEach(item => {
            if (item.requiredFlag == 1) {
              if ((item.valueType == 1 || item.valueType == 3) && item.longValue == "" && item.longValue == 'string') error.push(item.name)
              if (item.valueType == 0 && item.decimalValue == "") error.push(item.name)
              if (item.valueType == 2 && item.stringValue == "") error.push(item.name)
              if (item.valueType == 4 && item.enumItemName == "") error.push(item.name)
            }
          })
          if (error.length > 0) {
            this.$message.error(error.join('、') + '等字段必填')
            return;
          }

          // 自定义字段还需要再处理下
          tempSubject.fields = tempSubject.fields.map(item => {
            let temp = {
              fieldId: item.fieldId,
              showType: item.showType
            }
            if (item.valueType == 2) {
              temp.stringValue = item.stringValue
            }
            if (item.valueType == 0) {
              temp.decimalValue = Number(item.decimalValue)
            }
            if (item.valueType == 1 || item.valueType == 3) {
              temp.longValue = Number(item.longValue)
            }
            if (item.valueType == 4) {
              temp.enumItemName = item.enumItemName
            }

            return temp
          })

          let id = await subjectCreate(tempSubject)
          tempSubject.id = id;
          tempSubject.statusName = '待查勘'
          this.temp.subjects.push(tempSubject)
          this.temp.subjectIds = this.temp.subjects.map(item => item.id)
          this.$message.success({ message: '创建成功' })
          this.isibleDialogSubject = false
        } else {
          console.log('error submit!!');
          return false;
        }
      })
    },
    //点击添加评估对象
    async handleAddSubject() {
      this.tempSubject = JSON.parse(JSON.stringify(tempSubject))
      this.tempSubject.propertyType = this.propertyType
      this.tempSubject.propertyTypeName = transfromData(TARGET_TYPE_LIST, this.propertyType)
      this.isibleDialogSubject = true;
      // 请求字段接口，获取对象的字段
      let field = await fieldGetList({ objectType: 8, reportFlag: 1, propertyType: this.propertyType, pageCount: 999 });
      this.tempSubject.fields = field.list.map((item) => {
        return {
          fieldId: item.id,
          longValue: '', stringValue: '',
          decimalValue: '',
          enumItemName: '',
          showType: item.showType,
          valueType: item.valueType,
          name: item.name,
          relatedEnum: item.relatedEnum,
          requiredFlag: item.requiredFlag,
          valueUnit: item.valueUnit
        }
      })
    },
    //保存并关闭
    async handeSave(type) {

      //执行保存
      let temp = JSON.parse(JSON.stringify(this.temp))
      // 自定义字段还需要再处理下
      let fields = temp.fields.map(item => {
        let temp = {
          fieldId: item.fieldId
        }
        if (item.valueType == 2) {
          temp.stringValue = item.stringValue
        }
        if (item.valueType == 0) {
          temp.decimalValue = Number(item.decimalValue)
        }
        if (item.valueType == 1 || item.valueType == 3) {
          temp.longValue = Number(item.longValue)
        }
        if (item.valueType == 4) {
          temp.enumItemName = item.enumItemName
        }

        return temp
      })
      let { againType, customerCompanyBusinessEiid, customerUserId, files, methodTypeEiids,
        name, primaryUserId, purposeType, reportType, reviewUserId, secondaryUserId, subjectIds,
        submitFlag, writeUserId, evaluateTime, finishTime } = temp;

      if (this.dialogType == 'create') {
        await reportCreate({
          fields, againType, customerCompanyBusinessEiid,
          customerUserId, files, methodTypeEiids, name, primaryUserId,
          purposeType, reportType, reviewUserId, secondaryUserId,
          subjectIds, submitFlag, writeUserId
        })
      } else {
        await reportUpdate({
          id: temp.id,
          fields, customerCompanyBusinessEiid,
          files, methodTypeEiids, name, primaryUserId,
          reviewUserId, secondaryUserId,
          subjectIds, writeUserId, evaluateTime, finishTime
        })
      }

      this.$message.success({ message: '保存成功' })
      // 如果有关闭执行关闭
      if (type == 'close') {
        this.visibleDialog = false
      }
      this.getData();
    },
    //选择客户人员并赋值
    selectUserVal(val) {
      let user = this.UserList.filter(item => item.id == val)[0];
      this.temp.customerUserId = user.id
      this.temp.customerUser = user
      
    },
    //选择内部人员并赋值
    selectUserVal2(val){
      let user = this.UserList.filter(item => item.id == val)[0];
      this.temp[this.selectUserType] = user.id
      if(this.selectUserType=='primaryUserId')this.temp.primaryUser=user
      if(this.selectUserType=='secondaryUserId')this.temp.secondaryUser=user
      if(this.selectUserType=='reviewUserId')this.temp.reviewUser=user
      if(this.selectUserType=='writeUserId')this.temp.writeUser=user
    },
    //点击选择客户人员
    handleSelectUser() {
      this.visibleDialogUser = true
      this.paramsUser = {
        companyId: '',
        pageCount: 10,
        pageIndex: 0,
        realName: '',
        type: 2
      }
      this.getUserList();
    },
    //点击选择内部人员
    handleSelectUser2(type){
      this.visibleDialogUser2 = true
      this.selectUserType = type
      this.paramsUser = {
        companyId: '',
        pageCount: 10,
        pageIndex: 0,
        realName: '',
        type: 1
      }
      this.selectUser2 = '';
      this.getUserList();
    },
    //获取客户人员列表
    async getUserList() {
      let users = await userGetList(this.paramsUser)
      this.UserList = users.list;
      this.userTotal = users.totalCount;
    },
    //点击新增、编辑
    async handleAdd(type, row) {
      this.visibleDialog = true
      this.dialogType = type;
      if (type == 'create') {
        let field = await fieldGetList({ objectType: 7, templateFlag: 0, pageCount: 999 })
        this.temp = JSON.parse(JSON.stringify(temp))
        // 获取所有的报告自定义字段
        this.fieldList = field.list
        this.temp.fields = field.list.map(item => {
          item.fieldId = item.id;
          return item;
        })
      } else {
        this.getReportInfo(row.id)
      }

      //获取所有的业务类型
      let business = await enumInfo({ id: 36 })
      this.customerCompanyBusinessesList = business.items.filter(item => item.selectFlag == 1).map(item => {
        let name = item.name;
        let nowItem = JSON.parse(JSON.stringify(item));
        for (let i = 1; i < item.level; i++) {
          let parent = business.items.filter(aItem => aItem.id == nowItem.parentId);
          if (parent.length > 0) {
            name = parent[0].name + '-' + name
          }
          nowItem = parent;
        }
        return { label: name, value: item.id }
      })

      //获取所有的评估方法
      let methods = await enumInfo({ id: 41 })
      this.METHOD_TYPE_LIST = methods.items.map(item => {
        return { label: item.name, value: item.id }
      })

    },
    // 处理报告详情数据逻辑
    async getReportInfo(id) {
      // 查询报告详情接口
      let data = await reportInfo({ id })
      data.methodTypeEiids = data.methodTypeEiids.split(',').map(item => Number(item))
      data.subjects = data.subjects.map(item => {
        item.propertyTypeName = transfromData(TARGET_TYPE_LIST, item.propertyType)
        return item;
      })
      this.fieldList = data.majorFields.map(item => {
        return item.field
      })
      data.subjectIds = data.subjects.map(item => item.id)
      data.fields = data.majorFields.map(item => {
        item.valueType = item.field.valueType
        return item
      })
      if(data.finishTime==0){
        data.finishTime = ""
      }
      if(data.evaluateTime==0){
        data.evaluateTime = ""
      }
      this.temp = data
      //根据报告id，查询查勘列表
      let surveyList = await surveyGetList({ reportId: data.id, pageCount: 999 })
      this.temp.subjects = this.temp.subjects.map(item => {
        let survey = surveyList.list.filter(surveyItem => surveyItem.subject.id == item.id)[0]
        if (survey) {
          item.statusName = transfromData(SURVEY_STATUS_LIST, survey.status)
          item.survryId = survey.id
        }
        return item;
      })
    },
    handleSearch() {
      this.params.pageIndex = 0;
      this.getData();
    },
    async getData() {
      this.loading = true;
      let data = await reportGetList(this.params);
      this.loading = false;
      this.total = data.totalCount;
      this.list = data.list.map(item => {
        item.createTime = moment(item.createTime).format('YYYY-MM-DD HH:mm:ss')
        item.statusName = transfromData(REPORT_STATUS_LIST, item.status)
        return item;
      });
    },
    // 修改每页数量
    handleSizeChange(val, type) {
      if (type == 'paramsUser') {
        this.paramsUser.pageIndex = 0;
        this.paramsUser.pageCount = val;
        this.getUserList();
      }else if(type == 'paramsCase'){
        this.paramsUser.pageIndex = 0;
        this.paramsUser.pageCount = val;
        this.getCaseList();
      } else {
        this.params.pageIndex = 0;
        this.params.pageCount = val;
        this.getData();
      }

    },
    // 切换分页
    handleCurrentChange(val, type) {
      if (type == 'paramsUser') {
        this.paramsUser.pageIndex = val - 1;
        this.getUserList();
      }else if(type == 'paramsCase'){
        this.paramsCase.pageIndex = val - 1;
        this.getCaseList();
      } else {
        this.params.pageIndex = val - 1;
        this.getData();
      }

    },
  }
}
</script>
<style>
.dialog .el-dialog__body {
  padding-top: 0;
}

.form-grid {
  display: grid;
  grid-template-columns: 1fr 1fr;
  /* 两列 */
  gap: 10px;
  /* 间距 */
}

.dialogUser .el-radio__label {
  padding-left: 30px;
}
</style>
<style lang="scss" scoped>
.dashboard {
  &-container {
    margin: 30px;
    position: relative;

    .page {
      padding: 20px 0;
      text-align: center;
    }

    .dialog {
      .opt {
        margin-bottom: 10px;
      }

      .sub_title {
        text-align: center;
        background: #f5f5f5;
        height: 30px;
        line-height: 30px;
        margin-bottom: 10px;
        color: black;
        border: 1px solid #ddd;
      }

      .content {
        height: 500px;
        overflow-y: scroll;
        padding-right: 10px;
      }
    }
  }
}
</style>
